package com.android.manghe.common.webview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.android.base.frame.presenter.IView;
import com.android.base.frame.presenter.XPresenter;
import com.android.base.frame.title.ETitleType;
import com.android.base.frame.view.MVPActivity;
import com.android.base.tools.DisplayUtil;
import com.android.base.tools.StatusBarUtil;
import com.android.manghe.R;
import com.android.manghe.common.webview.util.InteractiveUtil;
import com.android.manghe.main.MainActivity;
import com.android.manghe.user.activity.LoginActivity;

/**
 * 用于支付的H5页面
 *
 * @author ZhangWeijun
 * @time 2018/6/8 14:05
 */
public class WebViewActivity extends MVPActivity<XPresenter<IView>> implements WebViewEventListener {
    private ProgressBar pbProgress;
    private WebViewFragment webViewFragment;
    private WebViewParameter parameter;
    private boolean pageWillBackToIndex = false;//返回点击返回按钮跳转到web首页
    private boolean isLoadSuccessful = true;//是否加载成功了
    private boolean isLoadFinished;//是否加载结束了

    private TextView tvCenter, tvLeft;

    private boolean isFromPush;

    private boolean isShowShortTime;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        webViewFragment.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onCreate(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected ETitleType showToolBarType() {
        return ETitleType.NO_TITLE;
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(this, 48f));
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this);
        findViewById(R.id.layoutTitleBar).setLayoutParams(lp);

        Intent intent = getIntent();
        parameter = (WebViewParameter) intent.getSerializableExtra("parameters");
        if (parameter == null) {
            throw new IllegalArgumentException("the WebViewParameter instance cannot be null");
        }

        isFromPush = intent.getBooleanExtra("isFromPush", false);
        isShowShortTime = intent.getBooleanExtra("isShowShortTime", false);
        initViews();
    }

    private void initViews() {
        tvCenter = findViewById(R.id.tv_center);
        tvLeft = findViewById(R.id.tv_left);
        findViewById(R.id.fl_title_bar).setBackgroundResource(R.color.white);

        Drawable drawable = getResources().getDrawable(R.mipmap.icon_back_black);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
        tvLeft.setCompoundDrawables(drawable, null, null, null);//画在左边
//        getTitleBar().setLeftIcon(R.mipmap.icon_back_black, v -> {
//            doBackAction();
//        }).setTitleAndStatusBgColor(ContextCompat.getColor(this, R.color.white));
        tvLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doBackAction();
            }
        });

        if (!parameter.isShowWebPageTitle() && !TextUtils.isEmpty(parameter.getCustomTitle())) {
            tvCenter.setText(parameter.getCustomTitle());
        }

        pbProgress = findViewById(R.id.pb_progress);
        pbProgress.setMax(100);
        if (parameter.isShowProgress()) {
            pbProgress.setVisibility(View.VISIBLE);
        }
        webViewFragment = WebViewFragment.newInstance(parameter, this);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, webViewFragment)
                .commitAllowingStateLoss();

        webViewFragment.setNeedKeyboardHandle(true);//需处理键盘弹出遮挡问题
    }


    @Override
    public void onProgressChange(int progress) {
        if (parameter.isShowProgress()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                pbProgress.setProgress(progress, true);
            } else {
                pbProgress.setProgress(progress);
            }
        }
    }

    @Override
    public void onReceivedTitle(String title) {
        if (parameter.isShowWebPageTitle()) {
            tvCenter.setText(title);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        isLoadFinished = true;
        if (parameter.isShowProgress()) {
            pbProgress.setVisibility(View.GONE);
        }
        if (isShowShortTime) {
            new Handler().postDelayed(() -> {
                finish();
            }, 2000);
        }
    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) {
        if (parameter.isShowProgress()) {
            pbProgress.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadError() {
        isLoadSuccessful = false;
    }

    @Override
    public void jsCallJava(String jsonParam) {
        EInteractiveActionType actionType = InteractiveUtil.convertActionType(jsonParam);
        if (null != actionType) {
            if (actionType == EInteractiveActionType.ToPay) {
            }
        }
    }

    @Override
    public void goToLogin() {
        finish();
        open(LoginActivity.class);
    }

    @Override
    public boolean shouldOverrideUrlLoading(String url) {
        return false;
    }

    @Override
    public void onBackPressed() {
        doBackAction();
    }

    @Override
    protected void onResume() {
        webViewFragment.resume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        webViewFragment.pause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        webViewFragment.destroy();
        super.onDestroy();
    }

    private void doBackAction() {
        if(isFromPush){
            open(MainActivity.class);
        }
        finish();
//        try {
//            if (pageWillBackToIndex) {
//                webViewFragment.backOrForward(-webViewFragment.getHistoryListSize() + 1);
//                pageWillBackToIndex = false;
//            } else {
//                if (parameter.isCanHistoryGoBackOrForward() && webViewFragment.canGoBack()) {
//                    webViewFragment.back();
//                } else {
//                    if (isLoadSuccessful && isLoadFinished) {
//                        setResult(RESULT_OK);
//                    }
//                    finish();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static void showActivity(Context context, WebViewParameter parameters) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        context.startActivity(intent);
    }

    public static void showNewTaskActivity(boolean isFromPush, Context context, WebViewParameter parameters) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        intent.putExtra("isFromPush", isFromPush);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void showActivityShortTIme(Context context, WebViewParameter parameters) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        intent.putExtra("isShowShortTime", true);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_web_view;
    }
}
